package it.antonio.ilpizze.swing.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.AbstractListModel;

public abstract class SimpleListModel<T> extends AbstractListModel implements Iterable<T> {

	private static final long serialVersionUID = 1L;

	protected List<T> list;

	public SimpleListModel(List<T> list) {
		super();
		this.list = list;
	}
	public SimpleListModel(T... array) {
		this(toList(array));
	}

	private static <T> List<T> toList(T... array){
		List<T> list = new ArrayList<T>();
		for(T t : array) list.add(t);
		return list;
	}
	
	public abstract String toDescriptionString(T obj);

	@Override
	public Object getElementAt(int i) {
		return toDescriptionString(list.get(i));
	}
	
	public void add(T element) {
		if (list.add(element)) {
			fireContentsChanged(this, 0, getSize());
		}
	}

	public T get(int row) {
		return list.get(row);
	}
	
	public void setList(List<T> list) {
		this.list = list;
		fireContentsChanged(this, 0, getSize());
	}
	
	public void clear() {
		list.clear();
		fireContentsChanged(this, 0, getSize());
	}

	public T remove(int arg0) {
		T element = list.remove(arg0);
		if(element != null){
			fireContentsChanged(this, 0, getSize());
		}
		return element;
	}

	@Override
	public int getSize() {
		return list.size();
	}
	
	@Override
	public Iterator<T> iterator() {
		return list.iterator();
	}
	
	public List<T> getList() {
		return list;
	}
}
